<template>
  <main-card-admin title="账号管理" :loading="loading" :tabs="tabs" :main-body-style-obj="{ paddingTop: '32px' }">
    <template #tool-btn>
      <a-button v-if="isAdmin && checkKey('admin-user-manage-admin-add')" type="primary" @click="openAddUser"> 添加管理员账号</a-button>
      <a-button v-if="!isAdmin && checkKey('admin-user-manage-student-add')" type="primary" @click="openAddUser"> 添加普通账号</a-button>
    </template>
    <template #screen-space>
      <a-row :align="'middle'" justify="space-between">
        <a-col class="mr-24">
          <a-select
            ref="select"
            v-model:value="pageForm.status"
            class="w-140"
            :options="statusOptions"
            :field-names="{ label: 'text', value: 'value' }"
            @change="getUserListData({ offset: 1 })"
          />
        </a-col>
        <a-col>
          <a-input
            v-model:value="pageForm.username"
            v-trim
            class="h-36"
            allow-clear
            placeholder="请输入用户名称"
            style="width: 328px"
            @keyup.enter="getUserListData({ offset: 1 })"
          >
            <template #prefix> <i class="iconfont icon-search-line"></i> </template>
          </a-input>
        </a-col>
      </a-row>
    </template>
    <div class="page">
      <GTable
        :columns="tableColumns"
        :data="userList"
        :page-form="pageForm"
        :loading="loading"
        :action-width="170"
        :action-option="tableActionOption"
        class="header-right-angle admin-table"
        @getDataList="getUserListData"
        @rowClick="previewUserDetail"
        @change="tableChange"
      >
        <template #createTime="{ record }"> {{ dateFormat(record.createTime) }}</template>
        <template #status="{ record }">
          <div v-if="record.status === '可用'" class="table__status">可用</div>
          <div v-else-if="record.status === '禁用'" class="table__status error">禁用</div>
        </template>
      </GTable>
    </div>
  </main-card-admin>
  <add-user
    v-model:visible-modal="showAddOrEditModal"
    v-model:user-id="editUserId"
    :is-admin="isAdmin"
    @ok="getUserListData({ offset: 1 })"
  />
  <user-detail v-model:visible-modal="showDetailModal" :is-admin="isAdmin" :view-item="currentUserDetail" />
</template>

<script setup lang="ts">
  import { message, Modal } from 'ant-design-vue'
  import { dateFormat } from 'g6-fn'
  import { createVNode, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  import WarnIcon from '@/components/icon/IconWarning/index.vue'
  import MainCardAdmin from '@/components/MainCardAdmin/index.vue'
  import { checkKey } from '@/directives/auth'
  import useList from '@/hooks/use-list'
  import { useConfigStore } from '@/store/config'

  import AddUser from '../components/AddUser.vue'
  import UserDetail from '../components/UserDetail.vue'
  import { IUser } from '../types'
  import { roleOptions } from './options'

  interface PageForm {
    username: string
    status: string | number
    columns: 'createTime' | 'updateTime' | ''
    order: 'desc' | 'asc'
  }
  interface Item {
    api: any
    text: string
    des: string
    params?: any
  }
  const route = useRoute()
  const router = useRouter()
  const config = useConfigStore()

  const isAdmin = route.path === '/user-manage/admin-list'

  const tabs = [
    {
      name: '普通用户',
      key: '/user-manage/student-list',
      auth: 'admin-user-manage-student-list'
    },
    {
      name: '管理员',
      key: '/user-manage/admin-list',
      auth: 'admin-user-manage-admin-list'
    }
  ]

  //根据角色使用不同的配置数据
  const pageApi = (() => {
    switch (route.path) {
      case '/user-manage/admin-list':
        return roleOptions['admin']
      case '/user-manage/student-list':
      default:
        return roleOptions['student']
    }
  })()

  // 表格
  const tableColumns = (() => {
    const arr = [
      {
        title: '用户名称',
        dataIndex: 'username',
        minWidth: 120
      },
      {
        title: '手机号',
        dataIndex: 'tel',
        minWidth: 120
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 100
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        isSort: true,
        width: 200
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        isSort: true,
        width: 200
      },
      {
        title: '操作',
        width: 170,
        dataIndex: 'tools'
      }
    ]
    // 管理员账号需显示角色名称
    if (isAdmin) {
      arr.splice(1, 0, {
        title: '角色',
        dataIndex: 'roleNames',
        minWidth: 120
      })
    }
    return arr
  })()

  const tableActionOption = {
    // 判断是什么类型的列表，来展示不同的操作按钮
    list: isAdmin
      ? [
          {
            auth: 'admin-user-manage-admin-edit',
            text: '编辑',
            onClick: (record: IUser) => handleUser(record.id, 'update')
          },
          {
            auth: 'admin-user-manage-admin-disable',
            dynamicText: (record: IUser) => (record.status === '可用' ? '禁用' : '启用'),
            onClick: (record: IUser) => handleUser(record.id, record.status === '可用' ? 'disabled' : 'open')
          },
          {
            auth: 'admin-user-manage-admin-edit',
            text: '删除',
            onClick: (record: IUser) => handleUser(record.id, 'delete')
          }
        ]
      : [
          {
            auth: 'admin-user-manage-student-edit',
            text: '编辑',
            onClick: (record: IUser) => handleUser(record.id, 'update')
          },
          {
            auth: 'admin-user-manage-student-disable',
            dynamicText: (record: IUser) => (record.status === '可用' ? '禁用' : '启用'),
            onClick: (record: IUser) => handleUser(record.id, record.status === '可用' ? 'disabled' : 'open')
          },
          {
            auth: 'admin-user-manage-student-edit',
            text: '删除',
            onClick: (record: IUser) => handleUser(record.id, 'delete')
          }
        ]
  }

  // 状态筛选
  const statusOptions = [
    {
      text: '全部状态',
      value: ''
    },
    {
      text: '可用',
      value: 1
    },
    {
      text: '禁用',
      value: 0
    }
  ]

  const {
    pageForm,
    dataList: userList,
    getDataList: getUserListData,
    loading
  } = useList<PageForm, IUser>(pageApi.listApi, {
    username: '',
    status: '',
    columns: '',
    order: 'desc'
  })

  const tableChange = (pagination: any, filters: any, sorter: any) => {
    pageForm.value.columns = sorter.field
    pageForm.value.order = sorter.order === 'ascend' ? 'asc' : 'desc'
    if (!sorter.order) {
      pageForm.value.columns = 'updateTime'
      pageForm.value.order = 'desc'
    }
    getUserListData({ offset: 1 })
  }

  const showAddOrEditModal = ref(false)
  const editUserId = ref('')

  const openAddUser = () => {
    showAddOrEditModal.value = true
  }

  const handleUser = (id: string, status: 'disabled' | 'open' | 'delete' | 'update') => {
    if (status === 'update') {
      editUserId.value = id
      return (showAddOrEditModal.value = true)
    }

    const statusOptions: Record<'disabled' | 'open' | 'delete', Item> = {
      disabled: {
        api: pageApi.disableApi,
        text: '禁用',
        des: '此账号将被禁用，请确认操作',
        params: {
          id,
          status: 0
        }
      },
      open: {
        api: pageApi.enableApi,
        text: '启用',
        des: '此账号将被启用，请确认操作',
        params: {
          id,
          status: 1
        }
      },
      delete: {
        api: pageApi.delApi(id),
        text: '删除',
        des: '此账号将被删除，且不可恢复，请确认操作'
      }
    }

    const handleItem = statusOptions[status]

    Modal.confirm({
      title: `确定${handleItem.text}？`,
      icon: createVNode(WarnIcon),
      content: handleItem.des,
      okText: handleItem.text,
      cancelText: '取消',
      centered: true,
      onOk: async () => {
        const res = await handleItem.api(handleItem.params)
        if (res.code === 'SYSTEM-100000') {
          message.success(`该用户已${handleItem.text}`)
          getUserListData()
        }
      }
    })
  }

  /* 查看的逻辑--------------------------------------------------------------------------------- */
  const showDetailModal = ref(false)
  const currentUserDetail = ref<IUser | null>(null)

  const previewUserDetail = (item: IUser) => {
    if (config.itemType === 'AI中台') {
      router.push({
        path: `/user-manage/detail/${item.id}`
      })
      return
    }
    currentUserDetail.value = item
    showDetailModal.value = true
  }
  /* --------------------------------------------------------------------------------- */

  getUserListData()
</script>

<style lang="less" scoped>
  @import '@/styles/mixins.less';
</style>
